package com.lovecws.mumu.controller.system.group;

import com.lovecws.mumu.common.core.enums.PublicEnum;
import com.lovecws.mumu.common.core.response.ResponseEntity;
import com.lovecws.mumu.shiro.realm.UserRealm;
import com.lovecws.mumu.system.entity.SysUser;
import com.lovecws.mumu.system.entity.SysUserGroup;
import com.lovecws.mumu.system.service.SysUserGroupService;
import com.lovecws.mumu.system.service.SysUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/group")
public class GroupMemberController {

	private static final Logger log = Logger.getLogger(GroupMemberController.class);

	@Autowired
	private SysUserService userService;
	@Autowired
	private SysUserGroupService userGroupService;
	@Autowired
	private UserRealm userRealm;

	/**
	 * 用户组分配角色
	 * @param groupId 用户组id
	 * @return
	 */
	@RequiresPermissions("system:group:memberView")
	@RequestMapping(value = { "/members" }, method = RequestMethod.GET)
	public String members(String groupId, HttpServletRequest request) {
		request.setAttribute("groupId", groupId);
		return "system/group/members";
	}

	/**
	 * 用户组分配角色
	 * @param groupId 用户组id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "/members/{groupId}" }, method = RequestMethod.GET)
	public Map<String, Object> userRole(@PathVariable String groupId) {
		// 分页查询
		List<SysUser> users=userService.querySysUserByGroupId(groupId, PublicEnum.NORMAL.value());
		Map<String, Object> page = new HashMap<String, Object>();
		page.put("total", users.size());
		page.put("rows", users);
		return page;
	}

	/**
	 * 用户组添加用户页面
	 * @param groupId 用户组id
	 * @return
	 */
	@RequestMapping(value = { "/memberAdd" }, method = RequestMethod.GET)
	public String memberAdd(String groupId,HttpServletRequest request) {
		//获取该分组下的用户列表
		List<SysUser> users=userService.querySysUserByGroupId(groupId, PublicEnum.NORMAL.value());
		//获取所有的用户列表
		List<SysUser> allUsers = userService.querySysUserByCondition(null, null, null, null, PublicEnum.NORMAL.value());
		
		List<SysUser> noSelectedUsers=new ArrayList<SysUser>();
		for (SysUser sysUser : allUsers) {
			boolean exists=false;
			for (SysUser user : users) {
				if(user.getUserId()==sysUser.getUserId()){
					exists=true;
					break;
				}
			}
			if(!exists){
				noSelectedUsers.add(sysUser);
			}
		}
		request.setAttribute("users", noSelectedUsers);
		request.setAttribute("groupId", groupId);
		return "system/group/memberAdd";
	}
	
	/**
	 * 保存组成员
	 * @param groupId 组id
	 * @param userId 用户id
	 * @param remark 描述
	 * @param privilage 权限
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("system:group:memberAdd")
	@RequestMapping(value = { "/memberAdd" }, method = RequestMethod.POST)
	public ResponseEntity saveMember(int groupId, int userId, String remark, String privilage, HttpServletRequest request) {
		try {
			SysUserGroup userGroup=new SysUserGroup();
			userGroup.setCreator(SecurityUtils.getSubject().getPrincipal().toString());
			userGroup.setGroupId(groupId);
			userGroup.setPrivilage(privilage);
			userGroup.setRemark(remark);
			userGroup.setUserId(userId);
			userGroupService.addSysUserGroup(userGroup);
			//当把当前用户添加到组成员的时候  用户的角色发生改变 请空当前登录用户的权限和角色信息
			userRealm.clearPermissionCache(String.valueOf(userId));
			return new ResponseEntity(200, "添加组成员成功", null);
		} catch (Exception e) {
			log.error(e);
			return new ResponseEntity(500,"添加组成员出现异常",null);
		}
	}
	
	/**
	 * 移除组成员
	 * @param userGroupId id
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("system:group:memberDelete")
	@RequestMapping(value = { "/memberDelete/{userGroupId}" }, method = RequestMethod.DELETE)
	public ResponseEntity memberDelete(@PathVariable String userGroupId) {
		try {
			userGroupService.deleteSysUserGroupById(userGroupId);
			return new ResponseEntity(200, "删除组成员成功", null);
		} catch (Exception e) {
			log.error(e);
			return new ResponseEntity(500,"移除组成员出现异常",null);
		}
	}
	
	/**
	 * 查看组成员详情
	 * @param userGroupId id
	 * @return
	 */
	@RequiresPermissions("system:group:memberView")
	@RequestMapping(value = { "/memberView/{userGroupId}" }, method = RequestMethod.GET)
	public String memberView(@PathVariable String userGroupId,HttpServletRequest request) {
		SysUserGroup userGroup=userGroupService.getSysUserGroupById(userGroupId);
		request.setAttribute("userGroup", userGroup);
		return "system/group/memberView";
	}
	
	/**
	 * 编辑组成员信息
	 * @param userGroupId id
	 * @return
	 */
	@RequiresPermissions("system:group:memberEdit")
	@RequestMapping(value = { "/memberEdit/{userGroupId}" }, method = RequestMethod.GET)
	public String memberEdit(@PathVariable String userGroupId,HttpServletRequest request) {
		SysUserGroup userGroup=userGroupService.getSysUserGroupById(userGroupId);
		request.setAttribute("userGroup", userGroup);
		return "system/group/memberEdit";
	}
	
	/**
	 * 更新组成员信息
	 * @param userGroupId 用户组和用户关系主键id
	 * @param privilage 权限
	 * @param remark 描述
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("system:group:memberEdit")
	@RequestMapping(value = { "/memberEdit" }, method = RequestMethod.PUT)
	public ResponseEntity updateMember(int userGroupId,String privilage,String remark,HttpServletRequest request) {
		try {
			SysUserGroup userGroup=new SysUserGroup();
			userGroup.setUserGroupId(userGroupId);
			userGroup.setEditor(SecurityUtils.getSubject().getPrincipal().toString());
			userGroup.setPrivilage(privilage);
			userGroup.setRemark(remark);
			userGroupService.updateSysUserGroupById(userGroup);
			return new ResponseEntity(200, "成功更新组成员信息", null);
		} catch (Exception e) {
			log.error(e);
			return new ResponseEntity(500,"编辑组成员信息出现异常",null);
		}
	}
}
